import Request from './request'
import apiList from './api'
// import {useStore} from '../store';
import Tools from '../common/tools'
import {RequestOptions,ResBody,apiParams} from './type';
// import {router} from '../router.js';
let cacheSessions:Record<string,any> = {}; //会话存储
export default function api(url:string, data:RequestOptions) {
	const request = new Request();
	let api = getApiObj(url);

	let cacheType = api.cacheType;
	const cacheKey = getCacheKey(url,data)
    
	request.interceptor.request((config:Record<string,any>, cancel:any) => { /* 请求之前拦截器 */
	    const token = uni.getStorageSync('token');
		let res;
		if( cacheType === 'local'){
			res = uni.getStorageSync(cacheKey);
		}else if( cacheType === 'session'){
			// console.log('request.interceptor cacheType',cacheType,cacheSessions[cacheKey])
			// 第一次session--要判断否则JSON.parse报错
			if(cacheSessions[cacheKey]) res = JSON.parse(cacheSessions[cacheKey]);
		}
		if(res){
			//调用者继续向下运行 cancel，本方法继续向下进行
			cancel('已获得请求值，不再请求',res,2)
			// console.log('已获得请求值，不再请求---',cacheType,cacheSessions,res);
			return;
		}
		if (api.auth && !token) {
            // store.commit('OUT_LOGIN');
			cancel('暂未登录,已阻止此次API请求~')
			setTimeout(()=>{
				uni.redirectTo({
					url:'/pages/index/loginWX'
				})
			},800)
		}
		if (token) {
			config.data={...data,token};
		}
		return config
	});

	request.interceptor.response((response) => { /* 请求之后拦截器 */
	       //200情况
        const data = response.data;
		if( cacheType === 'local'){
			(data && data.code === 1) &&  uni.setStorage({key: cacheKey,data: data})
		}else if(cacheType === 'session'){
			// console.log('request.interceptor response before--',data.RetStatus,data.RetData,cacheKey,cacheSessions[cacheKey],JSON.stringify(data.RetData || ''));
			(data && data.code === 1) && (cacheSessions[cacheKey] = JSON.stringify(data || ''));
			// console.log('request.interceptor response after----',cacheSessions[cacheKey])
		}
		return response;
	}, (error) => { // 除200都在
	    // console.log('error--',error)
	    if (error.statusCode) {
	        switch (error.statusCode) {
	            case 401: 
					// if(api.name === 'getUserInfo'){
					// 	uni.removeStorageSync('OpenID');
					// }else{
					// 	uni.removeStorageSync('OpenID')
					// 	uni.navigateTo({
					// 		url:'/pages/login/login'
					// 	})
					// }
					uni.removeStorageSync('OpenID')
					uni.navigateTo({
						url:'/pages/login/login'
					})
					// console.log('401---',api.name)
				break;
	            // 其他错误，直接抛出错误提示
	            default:
	                Tools.msg('网络繁忙 '+error.statusCode)
					break;
	        }
	       
	    }else{
			Tools.msg('请求失败~')
		}
		return error;
	})

	return request.request({
		url: api.url,
		data,
		method: api.method,
		isNprogress:api.isNprogress
	})

}

function getApiObj(url:string):apiParams {
	let apiArray = url.split(".");
	let api: apiParams|any = apiList;
	apiArray.forEach((v) => {
		api = api[v];
	});
	return api;
}
function getCacheKey(k:string='',data:any={}){
	// mydate.getDay()+ mydate.getHours()+ mydate.getMinutes()+mydate.getSeconds()+mydate.getMilliseconds()+ Math.round(Math.random() * 10000);
	return  "cache-"+k+JSON.stringify(data)
}

